package nachos.threads;

import nachos.machine.Lib;
import nachos.machine.Machine;

import java.util.LinkedList;

/**
 * An implementation of condition variables that disables interrupt()s for
 * synchronization.
 *
 * <p>
 * You must implement this.
 *
 * @see    Condition
 */
public class ComunicatorCondition extends Condition2
{
    private Condition2 condition;
    private Communicator communicator;
    private boolean isSpeaker = false;
    /**
     * Allocate a new condition variable.
     *
     * @param    conditionLock    the lock associated with this condition
     * variable. The current thread must hold this
     * lock whenever it uses <tt>sleep()</tt>,
     * <tt>wake()</tt>, or <tt>wakeAll()</tt>.
     */
    public ComunicatorCondition(Lock conditionLock, Communicator communicator, boolean isSpeaker)
    {
        super(conditionLock);
        this.communicator = communicator;
        this.isSpeaker = isSpeaker;
        condition = new Condition2(conditionLock);
    }

    public void sleep()
    {
        if (getNum() == 0)
        {
            String header = isSpeaker ? "speaker" : "listener";
            System.out.println(header + "Num=" + communicator.getListenerNum() + " , " + header + " wait");
            condition.sleep();
        }
    }

    public int getNum()
    {
        if(isSpeaker)
            return communicator.getSpeakerNum();
        else
            return communicator.getListenerNum();
    }

}
